#include <Stepper.h>

const int stepsPerRevolution = 2048;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int countab = 0;
int a = 999999, b = 0;
unsigned long count_low, buttonDelay = 1000;

void setup()
{
    myStepper.setSpeed(5);
    Serial.begin(9600);
    attachInterrupt(0, handler_falling, FALLING);   // pin2
    attachInterrupt(0, handler_low, LOW);
    attachInterrupt(0, handler_rising, RISING);
}

void loop()
{
    if (Serial.available() > 0)
    {
        int c = Serial.read();
        if (c == 1)
        {
            while (1)
            {
                if (analogRead(A0) >= a)
                    break;
                myStepper.step(32);
            }
        }
        else if (c == 2)
        {
            while (1)
            {
                if (analogRead(A0) <= b)
                    break;
                myStepper.step(-32);
            }
        }
    }
}

void handler_falling()
{
    if (countab == 0)
    {
        a = analogRead(A0);
        countab++;
    }
    else if (countab == 1)
    {
        b = analogRead(A0);
        countab = 0;
    }
}

void handler_low()
{
    count_low = millis();
}

void handler_rising()
{
    if (millis() - count_low >= buttonDelay)
    {
        a = 999999;
        b = 0;
    }
}